import React, { useState, useEffect, useRef } from "react";
import defaultImg from "@/assets/images/200.png";

interface LazyImageProps {
  src: string; // 图片的 URL
  alt?: string; // 可选的 alt 属性
}

const LazyImage: React.FC<LazyImageProps> = ({ src, alt }) => {
  const [isVisible, setIsVisible] = useState(false);
  const imgRef = useRef<HTMLImageElement | null>(null);
  const [imgSrc, setImgSrc] = useState(src);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([{ isIntersecting }]) => {
        if (isIntersecting) {
          console.log(imgRef, "进入可是去");
          //   加载失败
          (imgRef.current as HTMLImageElement).onerror = function () {
            setImgSrc(defaultImg);
          };
          setIsVisible(true);
          observer.unobserve(imgRef.current as HTMLImageElement);
        }
      },
      { threshold: 0 }
    );

    if (imgRef.current) {
      observer.observe(imgRef.current); // 观察图片 DOM 元素
    }

    return () => {
      if (imgRef.current) {
        observer.unobserve(imgRef.current); // 在组件卸载时取消观察
      }
    };
  }, []);

  return (
    <img
      ref={imgRef}
      src={isVisible ? imgSrc : ""} // 图片进入视口前，不设置 `src`
      alt={alt}
      style={{ objectFit: "cover" }}
    />
  );
};

export default LazyImage;
